<template>
  <div class="custom-page in-warehouse-order-info">
    <!-- 基础信息 -->
    <div>
      <div style="margin-bottom: 20px">
        <div class="descriptions-title">基本信息</div>
        <a-form-model
          ref="modelRef"
          :model="formState"
          :rules="rules"
          :labelAlign="`left`"
          :label-col="{ span: 5 }"
          :wrapper-col="{ span: 12 }"
        >
          <div>
            <a-row>
              <a-col :span="12">
                <a-form-model-item label="单据编号">
                  <a-input v-model="formState.orderNo" placeholder="请输入" :disabled="isInfo" />
                </a-form-model-item>
              </a-col>

              <a-col :span="12">
                <a-form-model-item label="订单状态">  
                  <a-tag v-if="formState.state == 1" color="pink">pink</a-tag>
                  <a-tag v-if="formState.state == 2" color="red">red</a-tag>
                  <a-tag v-if="formState.state == 0" color="orange">待上架</a-tag>
                  <a-tag v-if="formState.state == 4" color="green">已完成</a-tag>
                </a-form-model-item>
              </a-col>

              <a-col :span="12">
                <a-form-model-item label="入库类型" prop="orderType">
                  <a-radio-group v-model="formState.orderType" name="radioGroup" :disabled="isInfo">
                    <a-radio :value="0"> 采购 </a-radio>
                    <a-radio :value="1"> 调拨 </a-radio>
                    <a-radio :value="2"> 退回 </a-radio>
                  </a-radio-group>
                </a-form-model-item>
              </a-col>
              <template v-if="formState.orderType == 0">
                <a-col :span="12">
                  <a-form-model-item label="供应商" prop="supplierId">
                    <a-select
                      v-model="formState.supplierId"
                      style="width: 100%"
                      placeholder="请选择"
                      :options="supplierOptions"
                      :disabled="isInfo"
                    ></a-select>
                  </a-form-model-item>
                  <!-- :disabled="isInfo" -->
                  <!-- supplierOptions -->
                </a-col>
              </template>
              <!-- 入库类型为调拨时展示 -->
              <template v-if="formState.orderType == 1">
                <a-col :span="12">
                  <a-form-model-item label="调拨仓库" prop="sourceWarehouseId">
                    <a-select
                      v-model="formState.sourceWarehouseId"
                      style="width: 100%"
                      placeholder="请选择"
                      :options="warehouseOptionCom"
                      :disabled="isInfo"
                    ></a-select>
                  </a-form-model-item>
                </a-col>
              </template>
              <!-- 入库类型为回库时展示  -->
              <a-col v-if="formState.orderType == 2" :span="12">
                <a-form-model-item label="来源订单号" prop="sourceOrderId">
                  <a-input v-model="formState.sourceOrderId" placeholder="请输入" :disabled="isInfo" />
                </a-form-model-item>
              </a-col>

              <a-col :span="12">
                <a-form-model-item label="创建人">
                  <a-input v-model="formState.createBy" :disabled="isInfo" />
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item label="创建时间">
                  <a-input v-model="formState.createTime" :disabled="isInfo" />
                </a-form-model-item>
              </a-col>
            </a-row>
          </div>
        </a-form-model>
      </div>
      <div v-if="codeType == 2 && codeTags.length > 0" class="code-tag-wrap">
        <a-tag v-for="(l, i) in codeTags" :key="i" closable @close="(event) => tagDel(i, event)"> {{ l }} </a-tag>
      </div>
      <template v-if="pageType != 2">
        <div class="top-wrap">
          <a-input-search
            v-model="scanValue"
            placeholder="扫码录入"
            allowClear
            style="width: 400px"
            @search="addGood"
            ref="searchRef"
          >
            <a-button slot="enterButton" icon="scan"> </a-button>
          </a-input-search>
          <a-button
            style="margin-left: 20px"
            type="primary"
            @click="addOrder"
            :loading="loading"
            :disabled="!isAddOrder"
          >
            提交订单
          </a-button>
          <a-button style="margin-left: 20px" @click="reset()"> 重置 </a-button>
          <!-- <a-button style="margin-left: 20px"> 导出excel </a-button> -->
        </div>
        <div class="err-info">{{ errInfo }}</div>
        <div class="code-type">
          <div>条码类型：</div>
          <div>
            <a-radio-group v-model="codeType" :default-value="1">
              <a-radio :value="1"> 普通 </a-radio>
              <a-radio :value="2"> 多合一 </a-radio>
            </a-radio-group>
          </div>
        </div>
      </template>
    </div>

    <div class="bottom-wrap">
      <div v-if="pageType != 2" class="pack-module-header">
        <div>包裹管理（{{ packList.length }}）</div>
        <a-button type="primary" style="margin: 0 20px" @click="addPack()"> 新增包裹 </a-button>
        <div>
          <a-radio-group v-model="type" :default-value="1">
            <a-radio :value="1"> 一物一码 </a-radio>
            <a-radio :value="2"> 一码多物 </a-radio>
          </a-radio-group>
        </div>
      </div>
      <!-- 包裹列表 -->
      <div class="pack-list-wrap">
        <div v-if="packList.length > 0">
          <a-collapse v-model="activeKey" accordion>
            <a-collapse-panel v-for="(l, i) in packList" :key="i">
              <template #header="props">
                <div class="pack-header">
                  <div class="title">
                    包裹ID：{{ l.bar }}（{{ l.type == 1 ? '一物一码' : '一码多物' }}）<span style="margin-right: 12px"
                      >状态：{{ l.state == 0 ? '未生效' : '已绑定' }}</span
                    >数量：{{ l.type == 1 ? l.dataSource.length : l.sums }}
                    <a-button type="primary" style="margin-left: 14px" @click.stop="printPickBar(l)">
                      打印包裹条码
                    </a-button>
                  </div>
                  <a-popconfirm title="是否确认绑定该包裹?" ok-text="确定" cancel-text="取消" @confirm="bindPack(l, i)">
                    <a-button v-if="packConfirmFunc(l)" type="primary" style="margin-right: 14px" @click.stop>
                      确认
                    </a-button>
                  </a-popconfirm>
                  <a-form-model v-if="l.type == 2" :model="l">
                    <a-form-model-item prop="sums">
                      <div @click.stop>
                        <a-input-number
                          v-model="l.sums"
                          :disabled="l.dataSource.length === 0"
                          placeholder="请输入数量"
                          style="width: 120px; margin-right: 20px"
                        />
                      </div>
                      <!-- :min="1" :max="10" -->
                    </a-form-model-item>
                  </a-form-model>
                  <a-popconfirm title="是否删除该包裹数据?" ok-text="确定" cancel-text="取消" @confirm="delPack(l, i)">
                    <a-button @click.stop v-if="pageType != 2"> 删除 </a-button>
                  </a-popconfirm>
                </div>
              </template>
              <div class="good-list">
                <a-table
                  rowKey="bar"
                  :scroll="{ x: true }"
                  :columns="l.type == 1 ? oneToOneColumns : oneToManyColumns"
                  :data-source="l.type == 1 ? l.dataSource : l.dataSource.slice(0, 1)"
                  :pagination="false"
                >
                  <span slot="action" slot-scope="text, record, index">
                    <a-popconfirm
                      title="是否删除该条录入数据?"
                      ok-text="确定"
                      cancel-text="取消"
                      @confirm="delGood(record, index)"
                    >
                      <a-button :disabled="l.state != 0" type="link" size="small"> 删除 </a-button>
                    </a-popconfirm>
                  </span>
                  <template slot="cpmctymc" slot-scope="text, record, index">
                    <j-ellipsis :value="record.cpmctymc" :length="14" />
                  </template>
                  <template slot="ylqxzcrbarmc" slot-scope="text, record, index">
                    <j-ellipsis :value="record.ylqxzcrbarmc" :length="10" />
                  </template>
                </a-table>
              </div>
            </a-collapse-panel>
          </a-collapse>
        </div>
        <div v-else style="width: 500px">
          <a-empty />
        </div>
      </div>
    </div>
    <barCodePrint ref="codePrintRef" />
  </div>
</template>

<script>
const PACK = {
  obj: {
    id: undefined,
    num: 0,
    type: 1,
    state: 0,
    dataSource: [],
  },
  init(e) {
    return Object.assign(JSON.parse(JSON.stringify(this.obj)), e)
  },
}
const GOOD = {
  obj: {
    code: undefined,
    name: '',
  },
  init(e) {
    return Object.assign(JSON.parse(JSON.stringify(this.obj)), e)
  },
}
import JEllipsis from '@/components/jeecg/JEllipsis'
import { packGetCode, packBind, packDel, packGetOneToManyCode } from '@/api/pack.js'
import { queryGoodInfoById } from '@/api/good.js'
import { inOrderAdd, inOrderInfo } from '@/api/order.js'
import StoreUtils from '@/utils/im/StoreUtils.js'
import { stateObjToArray } from '@/utils/common.js'
import { mapState, mapGetters } from 'vuex'
import barCodePrint from '@/components/barCodePrint.vue'
const pageDateKey = 'inOrderData'
const defaultData = {
  errInfo: '', // 错误信息 如果未录入
  activeKey: 1,
  type: 1, // 1一物一码 2一码多物 包裹类型
  codeType: 1, // 1普通 2多和一
  packList: [],
  codeList: {}, // 条形码
  scanValue: '', // 扫码的数据
  loading: false,
  pageType: 0, // 0 添加 1编辑 2详情
  codeTags: [], // 多码合一的时候使用
  columns: [
    {
      title: '条形码',
      dataIndex: 'bar',
      key: 'bar',
      width: 340,
    },
    {
      title: '最小销售单元产品标识',
      dataIndex: 'zxxsdycpbs',
      key: 'zxxsdycpbs',
      width: 200,
    },
    {
      title: '医疗器械唯一标识编码体系名称',
      dataIndex: 'cpbsbmtxmc',
      key: 'cpbsbmtxmc',
      width: 140,
    },
    {
      title: '最小销售单元中使用单元的数量',
      dataIndex: 'zxxsdyzsydydsl',
      key: 'zxxsdyzsydydsl',
      width: 140,
    },
    {
      title: '医疗器械注册人/备案人名称',
      key: 'ylqxzcrbarmc',
      width: 200,
      scopedSlots: { customRender: 'ylqxzcrbarmc' },
    },
    {
      title: '产品名称/通用名称',
      key: 'cpmctymc',
      width: 200,
      scopedSlots: { customRender: 'cpmctymc' },
    },
    {
      title: '型号规格/包装规格',
      dataIndex: 'ggxh',
      key: 'ggxh',
      width: 90,
    },
    {
      title: '有效期',
      dataIndex: 'validity',
      key: 'validity',
      width: 90,
    },
    {
      title: '批次',
      dataIndex: 'batch',
      key: 'batch',
      width: 120,
    },
    {
      title: '91序号',
      dataIndex: 'serialNumberA',
      key: 'serialNumberA',
      width: 90,
    },
    {
      title: '21序号',
      dataIndex: 'serialNumberB',
      key: 'serialNumberB',
      width: 90,
    },
    {
      title: '操作',
      dataIndex: 'action',
      align: 'center',
      fixed: 'right',
      width: 80,
      scopedSlots: { customRender: 'action' },
    },
  ],
  formState: {
    orderNo: undefined, // 单据编号
    state:undefined, // 状态
    orderType: 0,
    supplierId: [],
    sourceWarehouseId: undefined, // 调拨仓库id
    sourceOrderId: undefined,
    createBy: undefined, // 创建人
    createTime: undefined, // 创建时间
  },
  rules: {
    supplierId: [{ required: true, message: '请选择' }],
    sourceWarehouseId: [{ required: true, message: '请选择' }],
    sourceOrderId: [{ required: true, message: '请输入' }],
  },
}
export default {
  data() {
    // 草稿箱功能
    var d = StoreUtils.getJson(pageDateKey) || {}
    this.$route.query.id && (d = {})
    return Object.assign(JSON.parse(JSON.stringify(defaultData)), d)
  },
  components: { JEllipsis, barCodePrint },
  computed: {
    ...mapState({
      supplierOptions: (s) => stateObjToArray(s.dictionary.supplier),
      warehouseOptions: (s) => stateObjToArray(s.dictionary.enableWarehouse),
    }),
    ...mapGetters(['userInfo']),
    // 过滤当前用户管理的仓库
    warehouseOptionCom() {
      const { userInfo } = this
      return this.warehouseOptions.filter((f) => f.value != userInfo.currWarehouse) || []
    },
    // 是否可以添加包裹  如果有未完成的包裹 不能添加
    isAddOrder() {
      // 判断是否可以添加入库订单
      let isAddOrder = true
      const { packList } = this
      if (packList.length == 0) return false
      packList.forEach((e) => {
        e.state == 0 && (isAddOrder = false)
      })
      return isAddOrder
    },
    oneToOneColumns() {
      const { pageType, columns } = this
      if (pageType != 2) {
        return columns
      } else {
        return columns.slice(0, columns.length - 1)
      }
    },
    oneToManyColumns() {
      const { pageType, columns } = this
      const arr = columns
        .slice(0, 3)
        // .concat([
        //   {
        //     title: '数量',
        //     key: 'num',
        //     scopedSlots: { customRender: 'num' },
        //   },
        // ])
        .concat(columns.slice(3))
      return arr.slice(0, arr.length - 1)
    },
    isInfo() {
      const { pageType } = this
      if (pageType == 2) {
        return true
      } else {
        return false
      }
    },
  },
  watch: {
    'formState.orderType': {
      handler(n, o) {
        this.$set(this.formState, 'orderNo', undefined)
        this.$set(this.formState, 'state', undefined)
        this.$set(this.formState, 'supplierId', [])
        this.$set(this.formState, 'sourceWarehouseId', undefined)
        this.$set(this.formState, 'sourceOrderId', undefined)
        this.$set(this.formState, 'createBy', undefined)
        this.$set(this.formState, 'createTime', undefined)
      },
      // deep: true,
    },
  },
  updated() {
    // 判断是否是创建的时候 是的话存入缓存
    if (this.$route.path.indexOf('add') > -1) {
      // 取消缓存功能
      // this.savaPageDate()
    }
  },
  mounted() {
    this.$store.commit('getSupplier')
    const id = this.$route.query.id
    const path = this.$route.path
    if (path.indexOf('info') > -1) {   // 详情 pageType = 2
      this.pageType = 2
    } else if (path.indexOf('add') > -1) {
      this.pageType = 0
    } else if (path.indexOf('edit') > -1) {
      this.pageType = 1
    }
    this.$nextTick(() => {
      if (id) {
        this.getInfo(id)
      }
    })
  },
  methods: {
    printPickBar(e) {
      this.$refs.codePrintRef.open({ code: e.bar })
    },
    tagDel(i, e) {
      e.preventDefault()
      this.codeTags.splice(i, 1)
      this.scanValue = this.codeTags.join('')
    },
    // 包裹确认按钮判断逻辑
    packConfirmFunc(l) {
      const { pageType } = this
      if (l.type == 1) {
        return l.dataSource.length > 0 && l.state == 0 && pageType != 2
      } else if (l.type == 2) {
        return l.dataSource.length > 0 && l.state == 0 && pageType != 2 && l.sums > 0
      }
    },
    reset() {
      const self = this
      Object.keys(defaultData).forEach((k) => {
        self[k] = defaultData[k] ? JSON.parse(JSON.stringify(defaultData[k])) : defaultData[k]
      })
      StoreUtils.setJson(pageDateKey, self.$data)
    },
    // 扫码添加商品进入包裹
    async addGood(_, e) {
      const { codeType, codeTags, activeKey, codeList, scanValue, packList } = this
      this.scanValue = undefined
      // 如果是多合一类型 并且是回车键 则增加标签
      if (codeType == 2 && e.type == 'keydown') {
        if (!scanValue) {
          this.codeTags = []
        } else {
          const addCode = scanValue.replace(codeTags.join(''), '')
          addCode && this.codeTags.push(addCode)
        }
        return
      }
      // 如果是多合一类型 并且是按钮点击 则提交数据 放过去 并且清空标签
      // 请求数据判断条形码是否已录入 录入的 清空输入框
      try {
        if (!scanValue) return

        // 判断是否重复扫码 判断是否有打开的包裹 当输入框条形码未消失 表示该商品录入失败
        if (!activeKey || packList.length == 0) {
          // 未打开包裹
          return
        }
        const openPackInfo = packList[activeKey - 1]
        const params = { udi: scanValue, inOrderType: this.formState.orderType }
        // 一码多物
        if (openPackInfo.type == 2) {
          const r = await queryGoodInfoById(params)
          const good = GOOD.init({ code: scanValue, ...r.result })
          this.$set(this.packList, activeKey - 1, { ...this.packList[activeKey - 1], dataSource: [good], sums: 0 })
        } else if (openPackInfo.type == 1) {
          if (!codeList[scanValue]) {
            // 不存在 未扫描 插入当前打开的包裹中
            const r = await queryGoodInfoById(params)
            const good = GOOD.init({ code: scanValue, ...r.result })
            // console.log('扫描后的商品信息', good)
            this.packList[activeKey - 1].dataSource.unshift(good)
            this.codeList[scanValue] = 1
          }
        }
        this.scanValue = undefined
        this.errInfo = undefined
      } catch (err) {
        // 系统中不存在 需要录入udi
        this.errInfo = `条形码：${scanValue} 录入失败`
        console.log('err', err)
      }
    },
    delGood(e, i) {
      const { activeKey } = this
      const self = this
      self.packList[activeKey - 1].dataSource.splice(i, 1)
      delete self.codeList[e.code]
      self.focusOnScan()
    },
    async addPack() {
      const self = this
      const { type } = this
      try {
        const API = {
          1: packGetCode,
          2: packGetOneToManyCode,
        }
        const r = await API[type]()
        self.packList.unshift(PACK.init({ ...r.result, type: self.type }))
        // 自动聚焦到扫描地方
        self.focusOnScan()
      } catch (_) {}
    },
    async delPack(e, i) {
      try {
        const params = { id: e.id }
        await packDel(params)
        this.packList.splice(i, 1)
        // 后期做一个包裹id 查询的接口 判断当前包裹是否被删除
      } catch (_) {}
    },
    async bindPack(e, i) {
      try {
        const params = JSON.parse(JSON.stringify(e))
        params.udiVtoLists = params.dataSource
        params.inOrderType = this.formState.orderType
        await packBind(params)
        this.$set(this.packList[i], 'state', 1)
      } catch (_) {}
    },
    async addOrder() {
      try {
        await this.$refs.modelRef.validate()
        const { formState } = this
        const params = { ...JSON.parse(JSON.stringify(formState)) }
        if (params.orderType * 1 != 0) {
          delete params.supplierId
        }
        const bars = this.packList.map((e) => e.bar).join(',')
        await inOrderAdd({ bars }, params)
        this.$message.success('完成')
        this.clearPageDate()
        this.$router.go(-1)
      } catch (_) {}
    },
    savaPageDate() {
      const self = this
      if (window.savaPageDate) {
        clearTimeout(window.savaPageDate)
      }
      window.savaPageDate = setTimeout(() => {
        StoreUtils.setJson(pageDateKey, self.$data)
      }, 100)
    },
    clearPageDate() {
      StoreUtils.setJson(pageDateKey, null)
    },
    async getInfo(id) {
      try {
        const params = { id }
        const r = await inOrderInfo(params)
        console.log(r); 
        this.packList = r.result.boxBarInfoVtoLists.map((e) => {
          e.type = e.productType * 1 + 1
          e.dataSource = e.udiVtoLists.map((c) => {
            return c
          })
          return e
        })
        console.log(this.packList);
        this.$set(this.formState, 'orderType', r.result.orderType * 1)
        this.$nextTick(() => {
          this.$set(this.formState, 'orderNo', r.result.orderNo)
          this.$set(this.formState, 'state', r.result.state)
          this.$set(this.formState, 'supplierId', [r.result.supplierId])
          this.$set(this.formState, 'sourceWarehouseId', r.result.sourceWarehouseId)
          this.$set(this.formState, 'sourceOrderId', r.result.sourceOrderId)
          this.$set(this.formState, 'createBy', r.result.createBy)
          this.$set(this.formState, 'createTime', r.result.createTime)
        })
      } catch (_) {
        console.log(_);
      }
    },
    // 聚焦扫描框
    focusOnScan() {
      this.$refs.searchRef.$refs.input.focus()
    },
  },
}
</script>

<style lang="scss" scoped>
.descriptions-title {
  font-size: 20px;
  font-weight: 650;
  margin-bottom: 20px;
}
.pack-module-header {
  display: flex;
  align-items: center;
  margin: 24px 0;
}
.pack-header {
  display: flex;
  align-items: center;
  .title {
    flex: 1;
  }
}
.err-info {
  font-size: 14px;
  color: red;
  margin: 24px 0;
}
.in-warehouse-order-info {
  :deep(.ant-table-thead > tr > th) {
    padding: 12px;
  }
}
.code-type {
  display: flex;
  align-items: center;
}
.ant-form-item {
  margin-bottom: 0;
}
.code-tag-wrap {
  margin-bottom: 20px;
}
</style>
